package org.nod.atgm.gameobjects;

import org.nod.atgm.GameManager;

import com.threed.jpct.Matrix;
import com.threed.jpct.Object3D;
import com.threed.jpct.Primitives;
import com.threed.jpct.SimpleVector;

public class ExplosionObject extends TexturedGameObject implements IRemovable{

	private static final int EXPLOSION_TRANSPARENCY = 100;
	private static final int EXPLOSION_PLANE_SIZE = 10;
	static final int PERIOD = 100; 
	int sumTime = 0;
	private Matrix texMat;
	int x = 0;
	int y = 0;
	protected boolean remove = false;
	private final float camX;
	private final float camZ;
	
	public ExplosionObject(SimpleVector translation, float camX, float camZ) {
		this.camX = camX;
		this.camZ = camZ;
		translation.y = 0; //Explosions are alays "sticked" to the ground now
//		translation.y = - EXPLOSION_PLANE_SIZE / 2; //Explosions are alays "sticked" to the ground now
		setPositionAndOrientaion(translation);
	}

	protected void setPositionAndOrientaion(SimpleVector translation) {
		getObject().translate(translation);
		translation.x -= camX;
		translation.z -= camZ;
		translation.y = 0;
		translation.normalize();
		setOrientation(translation,GameManager.INITIAL_VECTOR_UP);
	}

	@Override
	public void handleTimer(int time) {
		if (needsToRemove())
			return;
		sumTime += time;
		if (sumTime >= PERIOD) {
			sumTime = 0;
//			texMat.translate(0.25f*(float)x, 0.25f*(float)y, 0);
//			System.out.println("ExplosionObject.handleTimer() x = " + x + ",y = " + y);
			x++;
			if (x == 16) {
				remove = true;
				return;
			}
			texMat.set(3,0,0);
			texMat.set(3,1,0);
			texMat.translate(0.25f * x % 4, 0.25f * (x / 4),0);
//			if (x == 4) {
//				y++;
//				if (y == 4) {
//					remove = true;
//					return;
//				} else {
//					texMat.set(3,0,0);
//					texMat.set(3,1,0);
//					texMat.translate(0.25f * x % 4, 0.25f * (x / 4),0);
//							+
//							, 0);
//					x = 0;
//				}
//			}
//			texMat.translate(0.25f, 0, 0);
		}
	}
	
	@Override
	public void setTexture(String textureId) {
		super.setTexture(textureId);
		texMat = new Matrix();
		texMat.scalarMul(0.25f);
		texMat.translate(0.25f*(float)x, 0.25f*(float)y, 0);
		getObject().setTextureMatrix(texMat);
//		x++;
	}

	@Override
	protected Object3D createObject() {
		Object3D plane = Primitives.getPlane(1,EXPLOSION_PLANE_SIZE);
		plane.setTransparency(EXPLOSION_TRANSPARENCY);
		plane.translate(0, - EXPLOSION_PLANE_SIZE / 2.0f,0);
//		plane.calcTextureWrap();
		return plane;
	}

	@Override
	public boolean needsToRemove() {
		return remove;
	}

	public void setNeedsToRemove(boolean needsToRemove) {
	}

}
